package com.atwjy.process.service.impl;

import com.atguigu.model.process.ProcessTemplate;
import com.atguigu.model.process.ProcessType;
import com.atwjy.process.entity.OaProcessTemplate;
import com.atwjy.process.mapper.OaProcessTemplateMapper;
import com.atwjy.process.service.OaProcessTemplateService;
import com.atwjy.process.service.OaProcessTypeService;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.CollectionUtils;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * <p>
 * 审批模板 服务实现类
 * </p>
 *
 * @author atwjy
 * @since 2023-07-31
 */
@Service
public class OaProcessTemplateServiceImpl extends ServiceImpl<OaProcessTemplateMapper, ProcessTemplate> implements OaProcessTemplateService {
    @Autowired
    private OaProcessTemplateMapper processTemplateMapper;

    @Autowired
    private OaProcessTypeService processTypeService;
        @Override
        public IPage<ProcessTemplate> selectPage(Page<ProcessTemplate> pageParam) {
            LambdaQueryWrapper<ProcessTemplate> queryWrapper = new LambdaQueryWrapper<ProcessTemplate>();
            queryWrapper.orderByDesc(ProcessTemplate::getId);
            IPage<ProcessTemplate> page = processTemplateMapper.selectPage(pageParam, queryWrapper);
            List<ProcessTemplate> processTemplateList = page.getRecords();

            List<Long> processTypeIdList = processTemplateList.stream()
                    .map(processTemplate -> processTemplate.getProcessTypeId())
                    .collect(Collectors.toList());

            if(!CollectionUtils.isEmpty(processTypeIdList)) {
                Map<Long, ProcessType> processTypeIdToProcessTypeMap = processTypeService.list(new LambdaQueryWrapper<ProcessType>().in(ProcessType::getId, processTypeIdList)).stream().collect(Collectors.toMap(ProcessType::getId, ProcessType -> ProcessType));
                for(ProcessTemplate processTemplate : processTemplateList) {
                    ProcessType processType = processTypeIdToProcessTypeMap.get(processTemplate.getProcessTypeId());
                    if(null == processType) continue;
                    processTemplate.setProcessTypeName(processType.getName());
                }
            }
            return page;
        }
}
